#include <stdlib.h>
#include <crtdbg.h>
#include <windows.h>

#include "Model.h"
#include "Communicator.h"
#include "InputMessage.h"
#include "OutputMessage.h"

#pragma pack(push)
#pragma pack(1)
/// Raw data file header
typedef struct 
{
	DWORD dwLength; ///< Length in bytes of this structure
	DWORD dwSignature; ///< Raw data header signature
	char afpActiveFilter[8]; ///< Active filter
} RawDataStorageHeader;

/// Raw data message header
typedef struct 
{
	DWORD dwSignature; ///< Message signature
	unsigned short usRawDataLength; ///< Length in bytes of raw data (XML+binary)

} RawDataMessageHeader;
#pragma pack(pop)


void RunTestLoop(const char* filename, Model &model)
{
	HANDLE f;
	RawDataStorageHeader rdhdr;
	RawDataMessageHeader msghdr;
	char binaryData[16384];
	DWORD dwResult;
	DWORD MessageCounter = 0;

		f=CreateFile(filename,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
		if (INVALID_HANDLE_VALUE==f) return;
		ReadFile(f,&rdhdr,sizeof(rdhdr),&dwResult,NULL);
		model.SetTreeFormat(TF_XML);
		while(dwResult > 0)
		{
			ReadFile(f,&msghdr,sizeof(msghdr),&dwResult,NULL);
			ReadFile(f,binaryData,msghdr.usRawDataLength,&dwResult,NULL);
			// determine XML length
			char* dptr = *(unsigned short*)(binaryData) + binaryData+2;
			Communicator comm;
			std::string dstr("megaco");
			dstr+='\0';
			dstr.append(dptr,msghdr.usRawDataLength-(dptr-binaryData));
			pInputMessage nextMsg = IInputMessage::Create(MT_DECODE_REQUEST,dstr);

//			if (MessageCounter==5) DebugBreak();
			POutputMessage response = nextMsg->Process(&model);

			printf("\n\
				   ============================ %04d ============================================\n\
				   %s\n",MessageCounter,(response->Message()).c_str()+4);

			++MessageCounter;
		}
		CloseHandle(f);
}